package com.alex.seo.service.scheduler;

import java.util.Date;

import org.apache.commons.lang.StringUtils;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;

public abstract class SchedulerUtil {

	public static void scheduleJob(Scheduler scheduler, JobScheduler jobScheduler, JobDetail job) throws SchedulerException {
		Integer delay = jobScheduler.scheduleJob(0);
		if (delay != null) {
			Trigger trigger = createTrigger(job, delay, 0, 0);
			scheduler.scheduleJob(job, trigger);
		}
	}
	
	public static void rescheduleJob(JobExecutionContext context, Integer nextFireDelay, GenericJobContext genericJobContext) throws SchedulerException {
		Trigger trigger = createTrigger(context.getJobDetail(), nextFireDelay, genericJobContext.getTimesTriggered(), genericJobContext.getErrorCount());
		context.getScheduler().scheduleJob(trigger);
	}
	
	public static Trigger createTrigger(JobDetail job, int delay, int timesTriggered, int errorCount) {
		return TriggerBuilder.newTrigger()
				.withIdentity(formatTriggerName(job, timesTriggered, errorCount), job.getKey().getGroup())
				.startAt(new Date(System.currentTimeMillis() + delay))
				.forJob(job)
				.build();
	}
	
	private static String formatTriggerName(JobDetail job, int timesTriggered, int errorCount) {
		return job.getKey().getName() + " " + timesTriggered + ":" + errorCount;
	}

	public static GenericJobContext parseJobContext(JobExecutionContext context) {
		String triggerName = context.getTrigger().getKey().getName();
		int pos = triggerName.lastIndexOf(' ');
		if (pos < 0) {
			return null;
		}
		String[] parts = StringUtils.split(triggerName.substring(pos + 1), ":");
		return new GenericJobContext(Integer.parseInt(parts[0]), Integer.parseInt(parts[1])); 
	}
}
